package com.yc.demohoudun.web;

import com.yc.demohoudun.entiy.Result;
import com.yc.demohoudun.entiy.User;
import com.yc.demohoudun.mapper.UserMapper;
import com.yc.demohoudun.service.ServiceException;
import com.yc.demohoudun.service.UserService;

import jakarta.servlet.http.HttpSession;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Data
@RestController
public class UserAction {
    @Autowired
    public UserMapper userMapper;
    @Autowired
    public UserService userService;
  public   static String usernewName=null;

    @RequestMapping("/qeruyAll")
    List<User> queryAll(){
        return userMapper.selectAll();
    }

    @RequestMapping("/user/login")
    Result login(String username, String password, HttpSession session){

        try {
            User user = userService.login(username, password);
            user.setUsername(username);
            session.setAttribute("loginedUser", user);
            user.setSessionId(session.getId());

usernewName = user.getUsername();

            return new  Result(1,"登陆成功",user);
        } catch (ServiceException e) {
return  new Result(0,e.getMessage(),null);
        }

    }

    @RequestMapping("/user/getLoginedUser")
    Result getLoginUser(HttpSession session){
      User loginedUser = (User) session.getAttribute("loginedUser");
    if (loginedUser == null) {
        log.info("失败");
        return new Result(1,"登陆失败",loginedUser);
     }
    loginedUser.setSessionId(session.getId());
     return new Result(1,"登陆成功",loginedUser);
    }

    @RequestMapping("/user/logout")
    Result logout(HttpSession session){
        session.invalidate();
        return new Result(1,"退出成功",null);
    }

    @PostMapping("/user/regist")
    Result register(@RequestBody User user){
        return userService.saveUser(user);
    }

    @PostMapping("/user/forget-password/{email}")
    Result Fogetpassword(@PathVariable String  email){

        return userService.fogetPassword(email);
    }

    @GetMapping("/user/detail")
    Result UserDetail(@RequestParam String username){
        return userService.selectdatailAndproduct(username);  }
}
